package com.yf.ccdugtfood.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yf.ccdugtfood.R;
import com.yf.ccdugtfood.adapter.MyCommentAdapter;
import com.yf.ccdugtfood.bean.Comment;
import com.yf.ccdugtfood.util.Constant;

import java.lang.reflect.Type;
import java.util.List;

import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MyCommentActivity extends AppCompatActivity {
    private TextView tv_back,tv_title;
    private ListView comment_lv;
    private List<Comment> commentList;
    private MyCommentAdapter myCommentAdapter;

    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 2){
                if (msg.obj != null){
                    String commments = msg.obj.toString();
                    Gson gson = new Gson();
                    Type listType = new TypeToken<List<Comment>>(){}.getType();
                    commentList = gson.fromJson(commments.trim(),listType);
                    Log.i("sos",commments);
                    myCommentAdapter.setDate(commentList);
                    myCommentAdapter.notifyDataSetChanged();
                }
            }
        }
    };
    //返回删除结果
    private Handler dHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 3){
                String str = msg.obj.toString();
                if ("OK".equals(str.trim())){
                    Toast.makeText(MyCommentActivity.this,"删除成功!",Toast.LENGTH_SHORT).show();
                }else{
                    Toast.makeText(MyCommentActivity.this,"删除失败!!",Toast.LENGTH_SHORT).show();
                }
                showComment();
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_comment);
        initView();//初始化界面控件
        showComment();//获得评价信息
        deleteComment();//长按删除评价
    }

    private void initView() {
        tv_back = findViewById(R.id.tv_back);
        tv_title = findViewById(R.id.tv_title);
        comment_lv = (ListView)findViewById(R.id.my_comment_lv);
        tv_title.setText("我的评价");
        tv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        myCommentAdapter = new MyCommentAdapter(this);
        comment_lv.setAdapter(myCommentAdapter);
    }

    private void showComment() {
        SharedPreferences sp = getSharedPreferences("data", MODE_PRIVATE);
        String user_id = sp.getString("id", null);
        RequestBody body = new FormBody.Builder()
                .add("user_id",user_id)
                .build();
        OkHttpClient client = new OkHttpClient();
        String url = Constant.WEB_SITE + Constant.REQUEST_GETCOMMENT_URL; //访问服务器地址
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        final Call call = client.newCall(request);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Response response = call.execute();
                    String res = response.body().string();
                    Message msg = new Message();
                    msg.what = 2;
                    msg.obj = res;
                    mHandler.sendMessage(msg);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void deleteComment() {
        comment_lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
                AlertDialog dialog;
                AlertDialog.Builder builder = new AlertDialog.Builder(MyCommentActivity.this)
                        .setMessage("是否删除该评价？")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Comment comment = commentList.get(position);//获取长按item的id
                                String c_id = String.valueOf(comment.getId());
                                RequestBody body = new FormBody.Builder()
                                        .add("id",c_id)
                                        .build();
                                OkHttpClient client = new OkHttpClient();
                                String url = Constant.WEB_SITE + Constant.REQUEST_DETELECOMMENT_URL;//服务器访问路径
                                Request request = new Request.Builder()
                                        .url(url)
                                        .post(body)
                                        .build();
                                final Call call = client.newCall(request);
                                new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        try {
                                            Response response = call.execute();
                                            String res = response.body().string();
                                            Message msg = new Message();
                                            msg.what = 3;
                                            msg.obj = res;
                                            dHandler.sendMessage(msg);
                                        }catch (Exception e){
                                            e.printStackTrace();
                                        }
                                    }
                                }).start();
                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();//关闭对话框
                            }
                        });
                dialog = builder.create();//创建对话框
                dialog.show();//显示对话框
                return true;
            }
        });
    }
}
